package ar.com.cooker.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import ar.com.cooker.dao.ReviewDao;
import ar.com.cooker.model.Recipe;
import ar.com.cooker.model.Review;
import ar.com.cooker.model.User;

@Repository
@Transactional
public class ReviewDaoImpl implements ReviewDao {

	private EntityManager entityManager;
	@Override
	public void delete(Integer id) {
		Review r = getEntityManager().find(Review.class, id);
		getEntityManager().remove(r);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Review> findAll() {
		Query q = getEntityManager().createQuery("FROM Review r");
		return q.getResultList();
	}

	@Override
	public Review findById(Integer id) {
		return  getEntityManager().find(Review.class, id);
	}

	@Override
	public void save(Review t) {
		if((t.getUser() != null && t.getUser().getId() != null)&&(t.getRecipe() != null && t.getRecipe().getId() != null)){
			User u = getEntityManager().find(User.class, t.getUser().getId());
			Recipe p = getEntityManager().find(Recipe.class, t.getRecipe().getId());
			t.setRecipe(p);
			t.setUser(u);
			getEntityManager().persist(t);
		}else{
			//TODO excepcion
		}
	
	}

	@Override
	public void update(Review t) {
		if((t.getUser() != null && t.getUser().getId() != null)&&(t.getRecipe() != null && t.getRecipe().getId() != null) && t.getId() != null){
			getEntityManager().merge(t);
		}else{
			//TODO excepcion
		}
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

}
